Saturday, January 3, 2026

PYTHON PROGRAMMING UNIT 4: Tuples, Sets, and Dictionaries: Introduction, Tuples: Creating Tuples, Basic



 DR. AJAY KUMAR PATHAK

ASSISTANT PROFESSOR


READ  ALL THE NOTES CHAPTER WISE  OF PYTHON PROGRAMMING FOR B. SC IT SEM 5 F.Y.U.G.P. 


SUBJECT:- MJ-9 :(Th) PYTHON PROGRAMMING 

LEARN NOTES FROM HERE
PREPARED BY DR. AJAY KUMAR PATHAK 
©Copyrights MJ-9 PYTHON PROGRAMMING


Copyright © by Dr. Ajay kumar pathak

B. Sc IT SEMESTER 5 NOTES BASED ON NEP

SUBJECT : MJ - 9 (Th): PYTHON PROGRAMMING

(To be selected by the students from)

NOTES OF UNIT 4 OF PYTHON PROGRAMMING

Objectives

Understand computer programming concept using python language. Explore basic data types, control structures and standard library functions. Explore the basic data structures: List, Tuple, Sets, Dictionaries available in python. Learning Object oriented concept of programming and its

implementation in python.

Learning Outcomes:

At the end of the course, students will be able to–

·         Solve the basic mathematical problem using python programming.

·         Use basic data types control structures and utility functions from standard library for faster programming.

·         Use the basic and user defined data structures as per the need of problem. Design and implement the problem using OOP concept of python.

Detailed Syllabus

Unit 1

8 classes

Introduction to Python: Introduction, The History of Python, Features of python

language, Getting Started with Python, Programming Style and Documentation,

Programming Errors.

Elementary Programming: Introduction, Writing a Simple Program, Reading

Input from the Console, Identifiers, Variables, Assignment Statements, and

Expressions, Simultaneous Assignments, Named Constants, Numeric Data Types

and Operators, Evaluating Expressions and Operator Precedence, Augmented

Assignment Operators, Type Conversions and Rounding.

Unit 2

7 classes

Control Structures: Selections: Introduction, Boolean Types, Values, and Expressions, if Statements, Two-Way if-else Statements, Nested if and Multi-Way

if-else if-else Statements, Logical Operators, Conditional Expressions, Loops:

Introduction, The while Loop, The for Loop, Nested Loops, Keywords break and

continue

Unit 3

10 classes

Functions: Introduction, Defining a Function, Calling a Function, Functions

with/without Return Values, Positional and Keyword Arguments, Passing

Arguments by Reference Values, Modularizing code, The Scope of Variables,

Default Arguments, Returning Multiple Values.

Lists: Introduction, List Basics, Copying Lists, Passing Lists to Functions,

Returning a List from a Function, Searching Lists, Sorting, Processing Two-

Dimensional Lists, Passing Two-Dimensional Lists to Functions,

Multidimensional Lists.

Unit 4

10 classes

Tuples, Sets, and Dictionaries: Introduction, Tuples: Creating Tuples, Basic

Tuple Operations, Indexing and Slicing in Tuples, Tuple methods, Sets: Creating

Sets, Manipulating and Accessing Sets, Subset and Superset, Set Operations,

Comparing the Performance of Sets and Lists, Dictionaries: Creating a Dictionary,

Adding, Modifying, and Retrieving Values, Deleting Items, Looping Items, The

Dictionary Methods.

Unit 5

10 classes

Objects and Classes: Introduction, Defining Classes for Objects, Immutable

Objects vs. Mutable Objects, Hiding Data Fields, Class Abstraction and

Encapsulation.

Inheritance and Polymorphism: Introduction, Super classes and Subclasses,

Overriding Methods, The object Class, Polymorphism and Dynamic Binding, The

is instance function. Class Relationships: Association, Aggregation, composition.

Files and Exception Handling: Introduction, text input and output: opening a file,

Writing Data, Reading All Data from a File, Exception Handling.



UNIT 4 : TUPLES, SETS, AND DICTIONARIES

INTRODUCTION OF TUPLES:-  

Tuples in Python are immutable sequences that can hold a collection of heterogeneous (mixed) items. Defined by enclosing elements in parentheses, tuples allow for data storage without modification, making them useful for fixed data sets and as dictionary keys due to their hashability. Tuples store multiple items separated by commas in a single variable. Items are written with round brackets. There are various properties of tuples that should be considered while creating or performing the operations.

PROPERTIES:-

a)      Unchangeable- Tuples are immutable, which means we cannot change or add items after creating the tuple.

b)      Ordered- means that items are defined in an order that will not change after the insertion operation.

c)      Heterogeneous- A single tuple variable can contain different data types.

 

d)     Contains Duplicates- Allows to storage of duplicate data items.

BASIC TUPLE OPERATIONS:-

1.         Creating Tuples:

2.         Accessing Elements:

3.         Slicing Tuples:

4.         Concatenation:

5.         Repetition:

6.         Membership Testing:

(1).       CREATING TUPLES:- Tuples are created by enclosing elements in parentheses (), separated by commas.

EXAMPLE:-

# Note : In case of list, we use square # brackets []. Here we use round brackets ()

tup = (10, 20, 30)  # THIS IS A TUPLE

print(type(tup)) # TO CHECK THE TYPES OF TUPLE

print(tup) # PRINT THE TUPLE

IMMUTABLE IN TUPLES (HERE I WILL TRY TO MODIFY THE VALUE IN TUPLE, MEANS WE CAN NOT MODIFY) 

EXAMPLE:-

tup = (1, 2, 3, 4, 5)

# tuples are indexed

print(tup[1])

print(tup[4])

# tuples contain duplicate elements

tup = (1, 2, 3, 4, 2, 3)

print(tup)

# updating an element

tup[1] = 100 # here I am trying to modify the value at index 1

print(tup)

OUTPUT:

2

5

(1, 2, 3, 4, 2, 3)

Traceback (most recent call last):

  File "fileName.py", line 12, in <module>

    t[1] = 100

TypeError: 'tuple' object does not support item assignment

EXAMPLE WITHOUT SMALL BRACKETS ALSO CREATE A TUPLE BUT AFTER RUN WE WILL GET TUPLE VALUES


EXAMPLE:-

var = 1,2,3,4,”sandip”,40.50

print(type(var))

print(var)

OUTPUT:- (1,2,3,4,”sandip”,40.50) # AUTOMATICALLY CONVERTED IN TUPLE

NOTE:- IF WE WILL PROVIDE A SINGLE VALUE IN TUPLE WITHOUT SMALL BRACKETS  THAN IT WILL AUTOMATICALLY CONVERT IN OTHER DATA TYPES

EXAMPLE:-

var = 1

print(type(var) # here display int data type because here I have given a only single value

print(var)

OUTPUT:- 1 # this is not a tuple because in tuple should be small brackets 

NOTE:- BUT IF WE WANT TO DISPLAY A SINGLE VALUE AS A TUPLE THAN WE NEED TO GIVE A COMMA.

EXAMPLE:-

var = 1,   # Here automatically convert in tuple value

print(type(var) # here display class tuple  data type because here I have given a single value after a comma.

print(var)

 OUTPUT:- ( 1 ) # this is a tuple because in tuple should be small brackets 

(2).       ACCESSING ELEMENTS:-

ACCESS TUPLE USING NEGATIVE INDEX:- Here we will use the negative index within [].

EXAMPLE:-

tup = (10, 5, 20)

print("Value in tup[-1] = ", tup[-1])

print("Value in tup[-2] = ", tup[-2])

print("Value in tup[-3] = ", tup[-3])

OUTPUT:-

Value in tup[-1] =  20

Value in tup[-2] =  5

Value in tup[-3] =  10

CREATING AN EMPTY TUPLE:-

Example:

Tuple1 = ( )

print("\nEmpty Tuple is:", Tuple1)

Empty Tuple is: ()

NESTING OF PYTHON TUPLES:- A nested tuple in Python means a tuple inside another tuple.


EXAMPLE:-

# Code for creating nested tuples

tup1 = (0, 1, 2, 3)

tup2 = ('SANDIP', 'DEEPAK')

tup3 = (tup1, tup2)

print(tup3)

OUTPUT:-     ((0, 1, 2, 3), ('SANDIP', 'DEEPAK'))

(3).       REPETITION:-

REPETITION PYTHON TUPLES :-  We can create a tuple of multiple same elements from a single element in that tuple.

EXAMPLE:-

# Code to create a tuple with repetition

tup = ('AJAY',)*3

print(tup)

OUTPUT:-   ('AJAY', ‘AJAY', 'AJAY')

NOTE:- Try the above without a comma and check. You will get tuple3 as a string 'AJAYAJAYAJAY'.

(4).       SLICING TUPLES:- (Slicing means to display the value in between , means not from 1st to last, display only 2:4 means 2 se lekar four tak display karo)

SLICING TUPLES IN PYTHON:- Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.

In this example, we slice the tuple from index 1 to the last element.

In the second print statement, we printed the tuple using reverse indexing.

And in the third print statement, we printed the elements from index 2 to 4.

# code to test slicing

tup = (0 ,1, 2, 3)

print(tup[1:])  #1: means from 1 to last

print(tup[::-1])  # ::-1 means start from last element (3) because (–) minus means star from last element

print(tup[2:4]) # start from 2 index and go to 4th index

OUTPUT:-

(1, 2, 3)

(3, 2, 1, 0)

(2, 3)

FINDING THE LENGTH OF A PYTHON TUPLE:-  To find the length of a tuple, we can use Python's len() function and pass the tuple as the parameter.

 

EXAMPLE:-

# Code for printing the length of a tuple

tup = ('AJAY', 'KUMAR')

print(len(tup))

OUTPUT:-    2 # TOTAL NUMBER OF THE WORDS


CONVERTING A LIST TO A TUPLE:- We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.

EXAMPLE:-

# Code for converting a list and a string into a tuple

a = [0, 1, 2]  # THIS IS A LIST BECAUSE I HAVE ADDED THE SQUARE BRACKETS 

tup = tuple(a)

print(tup)

OUTPUT:-   (0, 1, 2)    # HERE ADDED THE SMALL BRACKETS

USING TUPLE CONSTRUCTOR:-

EXAMPLE:-

# Creating a tuple using the tuple() constructor

tup = tuple([7, 8, 9])

print(tup)

OUTPUT:-   (7, 8, 9)

(5).       CONCATENATION:- To join two or more tuples you can use the + operator: In Python, concatenating tuples means joining two or more tuples into a single tuple. Since tuples are immutable (cannot be changed after creation), concatenation is the way to combine their elements without altering original tuples.

(A)       The '+' operator can be used to add numeric values or concatenate strings.

EXAMPLE:-

my_tuple_1 = (11, 14, 0, 78, 33, 11)

my_tuple_2 = (10, 78, 0, 56, 8, 34)

print("The first tuple is : ")

print(my_tuple_1)

print("The second tuple is : ")

print(my_tuple_2)

my_result = my_tuple_1 + my_tuple_2

print("The tuple after concatenation is : " )

print(my_result)

OUTPUT:-

The tuple after concatenation is :

(11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)

EXAMPLE MIXED :-

tuple1 = ("a", "b" , "c")

tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2

print(tuple3)

OUTPUT:-

('a', 'b', 'c', 1, 2, 3)

(B).      Using sum():-     sum() function is used for adding numbers, but it can also concatenate multiple tuples when given a list of tuples and an EMPTY TUPLE () as the starting value. It works by treating the tuples like elements in a sequence and adding them together one by one.

t1 = (10, 30, 50)

t2 = (40, 60)

T = sum((t1, t2), ())

print(T)

OUTPUT:

(10, 30, 50, 40, 60)


( C)      Using itertools.chain() OR chain() function :- (THROUGH CHAIN() FUNCTION ALSO WE CAN CONCATENATE TOW OR MORE TUPLES OR LIST)    1ST OFF ALL IMPORT THE CHAIN() THAN IT WILL WORK.   itertools.chain() function from itertools module is used to iterate over multiple sequences as if they were a single continuous sequence. When applied to tuples it acts like a chain, linking all elements from each tuple together.

EXAMPLE:-

from itertools import chain

OR

import itertools chain

a = chain(range(5), range(10,15), range(20,50,5)) # here range() function, 1st range(5) will create a tuple  from 0 to 5, than 2nd range(10,15) will create a tuple 10 to 15 and 3td range(20,50,5) will create a tuple but step 5, here last 5 is the step,  like 20,25,30,35,40,45,50 OR simple also create a tuple see below

OR

tup1 = (0,1,2,3,4,)

tup2= (10,11,12,13,14)

for i in a:

            print(i,end=” “)

OUTPUT:

0 1 2 3 4 10 11 12 13 14

2ND METHOD FOR CONCATENATE

t1 = (1, 3, 5)

t2 = (4, 6)

T = tuple(itertools.chain(t1, t2))

print(T)

OUTPUT:-    (1, 3, 5, 4, 6)

EXPLANATION:

·         itertools.chain(t1, t2): creates an iterator that give up all elements from t1 followed by all elements from t2.

·         tuple(): converts the chained iterator into a single concatenated tuple.

(D).      Using list() + extend() methods:-       This method converts tuples to lists, merges them using extend() and then converts the result back to a tuple. It's a practical approach using list mutability.

EXAMPLE:-

t1 = (1, 3, 5) # THIS IS A TUPLE

t2 = (4, 6) # THIS IS A TUPLE

x = list(t1) # NOW CONVERTING IN LIST BY LIST() FUNCTION

y = list(t2) # NOW CONVERTING IN LIST BY LIST() FUNCTION

x.extend(y) # HERE I AM USING BY EXTEND() FUNCTION (x.extend(y) appends all elements of y to x. )

T = tuple(x)  # TUPLE(X) CONVERTS THE MERGED LIST BACK TO A TUPLE.

print(T)

OUTPUT:-           (1, 3, 5, 4, 6)

(E).      Using tuple() constructor  * operator  :-  Unpacking operator (*) along with the tuple() constructor combines multiple tuples into a single tuple. It's a clean approach that creates a new concatenated tuple without altering the original ones.

tup1 = (1, 3, 5) #*t1 and *t2 unpack the elements of two tuples.

tup2 = (4, 6)

T = tuple((*tup1, *tup2)) # (*t1, *t2) creates a new tuple by combining all unpacked elements.

print(T) # tuple() ensures result is a tuple.

OUTPUT:-   (1, 3, 5, 4, 6)



(F).      Make new ITEMS by sending two iterable objects into the function:

def myfunc(a, b):

  return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))

print(x)

#convert the map into a list, for readability:

print(list(x))

OUTPUT:-  ['appleorange', 'bananalemon', 'cherrypineapple']

 

MEMBERSHIP TESTING:- (Simple a item in list or tuple or dictionary this item present or not)       Membership testing in Python allows checking if a value exists within a sequence (like a list, tuple, set, string, or dictionary) using the in and not in operators. These operators are called membership operators, and they provide a simple way to check whether an item is present or absent in the collection.

There are two types :-

(1).       in :-  Returns True if a value exists within the container

(2).       not in:-  Returns True if a value does not exist within the container

EXAMPLE

(1).       in :-  Returns True if a value exists within the container

# Take input for elements in list (dynamic input)

items = input("Enter a few items separated by comma: ").split(",")

item_to_check = input("Enter an item to check membership: ")

# Membership testing

if item_to_check in items:

    print(f"{item_to_check} is present in your list!")

else:

    print(f"{item_to_check} is not present in your list!")

 

(2).       not in:-  Returns True if a value does not exist within the container

 

# Take a list of items as input from the user (separated by spaces)

items = input("Enter list items separated by spaces: ").split()

# Take the value to check

value = input("Enter a value to check: ")

 

# Check membership using 'in'

if value in items:

    print(f"{value} is present in the list.")

else:

    print(f"{value} is NOT present in the list.")

 

# CHECK MEMBERSHIP USING 'NOT IN'

if value not in items:

    print(f"Confirmed, {value} is not in the list.")

else:

    print(f"Confirmed, {value} is indeed in the list.")

LIST DECLARATION EXAMPLES:

# Get input from the user

user_value = input("Enter a value to check: ")

# List to test membership

my_list = ["apple", "banana", "cherry"]

# Membership test

if user_value in my_list:

    print(f"{user_value} is in the list!")

else:

    print(f"{user_value} is NOT in the list.")



TUPLE METHODS (OR FUNCTION)  :-    In Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists since the value of the items stored in the list can be changed whereas the tuple is immutable and the value of the items stored in the tuple cannot be changed. A tuple can be written as the collection of comma-separated values enclosed with the small brackets. It is Ordered, Immutable, Allows duplicate values.

(Unlike Python lists, tuple does not support various methods or functions such as append(), remove(), extend(), insert(), reverse(), pop(), and sort() because of its immutable nature.  )

SYNTAX:-   Tuple= (value1, value2…)

EXAMPLE:-

T1 = ()

T2 = (10, 30, 20, 40, 60)

T3 = ("C", "Java", "Python")

T4 = (501,"abc", 19.5)

T5 = (90,)

print(T1)

print(T2)

print(T3)

print(T4)

print(T5)

OUTPUT:-

()

(10, 30, 20, 40, 60)

('C', 'Java', 'Python')

(501, 'abc', 19.5)

(90,)

TUPLE METHODS OR  FUNCTIONS  :-  

len(), max() , min() , tuple(), sum(), sorted(), index(), count(), all(), any()

(1).       len():-  In Python len() is used to find the length of tuple, which if given as an argument to the function.  i.e it returns the number of items in the tuple.

SYNTAX:-    len(tuple)

EXAMPLE:-

num=(1,2,3,4,5,6)

print(“length of tuple :”,len(num))

OUTPUT

length of tuple : 6

 

INPUT EXAMPLE:-

# len() - counts number of elements in tuple

tup = tuple(input("Enter tuple elements (space-separated): ").split())

print("Length (int):", len(tup))  # Output type: int

OUTPUT:-

Enter tuple elements (space-separated): apple orange banana

Length (int): 3

 

 (2).      max():- In Python max() is used to find maximum value in the tuple.

SYNTAX:-    max(tuple)

EXAMPLE:

num=(1,2,3,4,5,6)

lang=('java','c','python','cpp')

print("Max of tuple :",max(num))

print("Max of tuple :",max(lang))

OUTPUT:

Max of tuple : 6

Max of tuple : python


EXAMPLE WITH INPUT

# max() - finds largest element in tuple of numbers

tup = tuple(map(int, input("Enter numbers for tuple (space-separated): ").split()))

print("Max (int):", max(tup))  # Output type: int

OUTPUT

Enter numbers for tuple (space-separated): 5 1 9 3

Max (int): 9

(3).       min():- In Python min() is used to find minimum value in the tuple.

SYNTAX:- min(tuple)

EXAMPLE:-

num=(1,2,3,4,5,6)

lang=('java','c','python','cpp')

print("Min of tuple :",min(num))

print("Min of tuple :",min(lang))

OUTPUT:-

Min of tuple: 1

Min of tuple : c

 

EXAMPLE WITH INPUT

# min() - finds smallest element in tuple of numbers

tup = tuple(map(int, input("Enter numbers for tuple (space-separated): ").split()))

print("Min (int):", min(tup))  # Output type: int

OUTPUT

Enter numbers for tuple (space-separated): 5 1 9 3

Min (int): 1

(4).       sum():-  This function returns the sum of all values of the tuple if all values belong to the same data type. If we try to apply the sum() on a tuple with different data types we will get an error because values of different data types cannot be added.

SYNTAX:- sum(tuple)

EXAMPLE:

num=(1,2,3,4,5,6)

print(“sum of tuple items :”,sum(num))

OUTPUT:-   sum of tuple items: 21

 

EXAMPLE WITH INPUT

# sum() - sums all numbers in tuple

tup = tuple(map(int, input("Enter numbers for tuple sum (space-separated): ").split()))

print("Sum (int):", sum(tup))  # Output type: int

OUTPUT

Enter numbers for tuple sum (space-separated): 1 2 3 4

Sum (int): 10

 


(5).       sorted():-   This function returns the version of the tuple in the form of a list with all elements arranged in increasing order. This is the case if all values belong to the same data type.

If we try to apply the sorted() on a tuple with different data types we will get an error because values of different data types cannot be compared. This function does not affect the order of elements in the tuple, it only returns the arranged version.

In python, sorted (tuple) function is used to sort all items of tuple in an ascending order. It also sorts the items into descending and ascending order. It takes an optional parameter 'reverse' which sorts the tuple into descending order.

SYNTAX:-  sorted (tuple[,reverse=True])

EXAMPLE:-

num=(1,3,2,4,6,5)

lang=('java','c','python','cpp')

print(sorted(num))

print(sorted(lang))

print(sorted(num,reverse=True)) # IN REVERSE ORDER 

OUTPUT:-

(1, 2, 3, 4, 5, 6)

('c', 'cpp', 'java', 'python')

(6, 5, 4, 3, 2, 1)

EXAMPLE WITH INPUT

# sorted() - returns new sorted tuple (numbers)

tup = tuple(map(int, input("Enter numbers to sort tuple (space-separated): ").split()))

sorted_tup = tuple(sorted(tup))

print("Sorted tuple (tuple):", sorted_tup)  # Output type: tuple

OUTPUT

Enter numbers to sort tuple (space-separated): 3 1 4 2

Sorted tuple (tuple): (1, 2, 3, 4)

(6)        tuple (sequence):-    The tuple() method takes sequence types and converts them to tuples. This is used to convert a given string or list into tuple.

SYNTAX:-    tuple(sequence)

EXAMPLE:-

str="python"

tuple1=tuple(str) # It will display with separate  commas 

print(tuple1)

num=[1,2,3,4,5,6]

tuple2=tuple(num)

print(tuple2)

OUTPUT:-

('p', 'y', 't', 'h', 'o', 'n')

(1, 2, 3, 4, 5, 6)

EXAMPLE WITH INPUT

# tuple() - create tuple from input elements

tup = tuple(input("Enter elements to create tuple (space-separated): ").split())

print("Tuple (tuple):", tup)  # Output type: tuple

OUTPUT

Enter elements to create tuple (space-separated): cat dog fish

Tuple (tuple): ('cat', 'dog', 'fish')


(7).       count():-  (Returns the number of times a specified value occurs in a tuple)  In python count() method returns the number of times element appears in the tuple. If the element is not present in the tuple, it returns 0.

SYNTAX:-  tuple.count (item)

EXAMPLE:-

num=(1,2,3,4,3,2,2,1,3,4,5,7,8)

cnt=num.count(2)       # count 2 only

print("Count of 2 is:",cnt)

cnt=num.count(10)  # count 10 only 

print("Count of 10 is:",cnt)

OUTPUT:-

Count of 2 is: 3

Count of 10 is : 0

EXAMPLE WITH INPUT

# count() - count occurrences of element in tuple

tup = tuple(input("Enter elements for tuple (space-separated): ").split())

ele = input("Enter element to count: ")

print("Count (int):", tup.count(ele))  # Output type: int

OUTPUT

Enter elements for tuple (space-separated): red blue green blue

Enter element to count: blue

Count (int): 2

(8)        index():-  (Searches the tuple for a specified value and returns the position of where it was found )  In python index () method returns index of the passed element. This method takes an argument and returns index of it. If the element is not present, it raises a ValueError.

If tuple contains duplicate elements, it returns index of first occurred element.

This method takes two more optional parameters start and end which are used to search index within a limit.

SYNTAX:-  tuple.index(x[, start[, end]])

EXAMPLE:-

lang = ('p', 'y', 't', 'h', 'o','n','p','r','o','g','r','a','m')

print("index of t is:",lang.index('t'))

print("index of p is:",lang.index('p'))

print("index of p is:",lang.index('p',3,10))

print("index of p is:",lang.index('z')

OUTPUT:-

index of t is: 2

index of p is: 0

index of p is: 6

ValueError: 'z' is not in tuple.

EXAMPLE WITH INPUT

# index() - find index of an element in tuple

tup = tuple(input("Enter elements for tuple (space-separated): ").split())

ele = input("Enter element to find index: ")

print("Index (int):", tup.index(ele))  # Output type: int

OUTPUT

Enter elements for tuple (space-separated): red blue green blue

Enter element to find index: blue

Index (int): 1



(9).       all():-   This function checks if all the elements are not empty or 0 and returns either True or False. It returns False if any of the elements is empty or 0. It can work on any tuple.

EXAMPLE:-

tup=(-1,'s',5,6,'t')

all(tup)

tup=('',0,'t',2,5.6)

all(tup)

OUTPUT

True

False

EXAMPLE WITH INPUT

# all() - check if all bool values True in tuple (input: True or False)

tup = tuple(x == "True" for x in input("Enter True/False values (space-separated): ").split())

print("All True (bool):", all(tup))  # Output type: bool

OUTPUT

Enter True/False values (space-separated): True True False

All True (bool): False

(10).     any():-   This function checks if any of the elements are not empty or 0 and returns either True or False. It returns False only if all of the elements are empty or 0. It can work on any tuple.

EXAMPLE :-

tup=(-1,'s',5,6,'t')

any(tup)

tup=('','t',3,5.6,0)

any(tup)

tup=('','',0,0,'')

any(tup)

OUTPUT:-

True

True

False

EXAMPLE WITH INPUT

# any() - check if any bool value True in tuple

tup = tuple(x == "True" for x in input("Enter True/False values (space-separated): ").split())

print("Any True (bool):", any(tup))  # Output type: bool

OUTPUT

Enter True/False values (space-separated): False True False

Any True (bool): True


SETS:-     

SETS:-    A Set in Python is used to store a collection of items with the following properties.

a)      The various all items enclosed within the curly braces

b)      Mutable, meaning we can add or remove elements after their creation, the individual elements within the set cannot be changed directly.

c)      An unordered (means without sequence we can store the items)   collection. When we access all items, they are accessed without any specific order.

d)     we cannot directly access any element of the set by the index

e)       No duplicate elements. If try to insert the same item again, it overwrites previous one.

f)       Internally use hashing that makes set efficient for search, insert and delete operations. It gives a major advantage over a list for problems with these operations.

 

EXPLANATION ALL PROPERTIES OF SET

(INSERTION ORDER IS NOT PRESERVED , MEANS SEQUENCE KO MAINTAIN NAHI KARTA HAI, MEANS JIS SEQUENCE ME DATA INPUT KARENGE US SEQUNCE ME OUTPUT NAHI DISPLAY KAREGA, SEE BELOW EXAMPLE)

(1)        CREATING SETS:-      The set can be created by enclosing the comma separated items with the curly braces.

SYNTAX:-   set={value1, value2….}

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} 

print(Days) 

print(type(Days)) 

print("Looping through the set elements ... ") 

for i in Days: 

    print(i)

NOTE:-  IF WE WILL CREATE A EMPTY SET WITHOUT THE ITEMS , SO THAT IS NOT A SET THAT IS A dictionary ,   LIKE set1={}, WHEN I WILL CHECK THERE TYPES (DATA TYPES print(type(set1))  ) IT WILL DISPLAY <class ‘dict’> . THEREFORE SET MUST BE LIKE set1= {1,20,40,”ABC”,20.30}, BUT IF WANT TO MAKE A EMPTY SET THAN WRITE CODE LIKE set1=set{}, NOW CHECK THERE TYPES IT WILL DISPLAY <class ‘set’>

OUTPUT

{" Wednesday", "Tuesday", " Sunday", " Friday",  " Thursday", " Saturday",” Monday

 “}  # this is not a sequence of the entered items (yeh sequence me display nahi karta hai yeh eska properties hai)

 

Looping through the set elements...

Wednesday

Tuesday

Sunday

Friday

Thursday

Saturday

Monday


EXAMPLE WITH INPUT

# Taking input from the user separated by spaces

user_input = input("Enter elements separated by space: ")

var=user_input

print({user_input})

EXAMPLE 3

# Taking input from the user separated by spaces

user_input = input("Enter elements separated by space: ")

# Splitting the input string into a list of elements

elements_list = user_input.split()   #The input string is split into a list.

# Creating a set from the list (removes duplicates automatically)

user_set = set(elements_list)

# Printing the resulting set

print("Set created from your input:", user_set)

(2).       INDEXING AND SLACING IS NOT WORK:- (we con not access any value by the index number)

EXAMPLE:-

var={10,’ajay’,20,30}

print(var(1) 

#  After run the program we will get a error (TypeError ‘set’ object is not subscriptable) because we are trying  to  access value  by the index number.

 (3).      SLICING ALSO NOT BE DONE :- (means, ek range me data ko ham display nahi kara sakte hai)

EXAMPLE:-

var={1,2,”ajay”3,4,”sandip”5,6,7,8}

print(3:5) # here also display a error because slicing is not allowed in set

(4).       HETEROGENEOUS DATA ARE  ALLOWED :-

EXAMPLE:- var={1,2,”ajay”,4.5,”sandip”,40.50}


(5).       DUPLICATE VALUES ARE NOT ALLOWED IN SET:-

EXAMPLE:-

var={1,2,”ajay”3,4,”ajay”5,6,7,8}

print(var)

OUTPUT:-   var={1,2,”ajay”3,4,5,6,7,8} # here we will get without ajay words are repeated

(6)        IT CHANGEABLE NATURE (MEANS MUTABLE NATURE):-

EXAMPLE:- var={1,2,”ajay”3,4,5,6,7,8}

var.add(“Dr. Ajay Kumar Pathak”) #here in python have a add() method , than through add() method we can insert values in set. By add() method we can insert only one value at a time.

var.update([“Dr. Ajay Kumar Pathak”, “MRS KMPM VC”]) #here in python have a update() method , than through update() method we can insert values in set. By update() method we can insert more than one value at a time.

print(var)

OUTPUT;-

1, “Dr. Ajay Kumar Pathak“, 2,”ajay”3,4,5,6,7,8

1, “Dr. Ajay Kumar Pathak“,“MRS KMPM VC”, 2,”ajay”3,4,5,6,7,8}

 

TYPE CASTING WITH PYTHON SET METHOD:-   The Python set() method is used for type casting.

# typecasting list to set

s = set(["a", "b", "c"])

print(s)

# Adding element to the set

s.add("d")

print(s)

OUTPUT

{'c', 'b', 'a'}

{'d', 'c', 'b', 'a'}

SET OPERATORS:- In Python, we can perform various mathematical operations on python sets like union, intersection, difference, etc

Operator

Description

|

Union Operator

&

Intersection Operator

-

Difference Operator:



(1).       Union ( | ) Operator (or operation ) :- The union of two sets are calculated by using the or ( | ) operator (or you can also write union instead of | (pipe operator) ). The union of the two sets contains the all the items that are present in both the sets.(Means duplicates values will ignore)

EXAMPLE:-

Days1={"Mon","Tue","Wed","Sat"}

Days2={"Thr","Fri","Sat","Sun","Mon"}

print(Days1 | Days2)

OUTPUT:

{'Thr', 'Fri', 'Sun', 'Tue', 'Wed', 'Mon', 'Sat'}

 

EXAMPLE 2 USE OF UNION :-

# LIKE {1,2}{2,3}={1,2,3}

set1 = {1, 2, 3}

set2 = {3, 4, 5}

set3 = {6, 8, 9}

set4 = {9, 45, 73}

union_set1 = set1.union(set2)   #USE OF UNION

union_set2 = set3 | set4     #USE OF PIPE |  OPERATOR

print ('The union of set1 and set2 is', union_set1)

print ('The union of set3 and set4 is', union_set2)

OUTPUT:-

The union of set1 and set2 is {1, 2, 3, 4, 5}

The union of set3 and set4 is {73, 6, 8, 9, 45}

 

(2).       Intersection (&) Operator:- The & (intersection) operator is used to calculate the intersection of the two sets in python. The intersection of the two sets are given as the set of the elements that common in both sets. (ONLY COMMON VALUES WILL DESPLAY, The resulting set contains only the elements present in both sets)

EXAMPLE:-

Days1={"Mon","Tue","Wed","Sat"}

Days2={"Thr","Fri","Sat","Sun","Mon"}

print(Days1 & Days2)

OUTPUT:-      {'Mon', 'Sat'}

 

EXAMPLE 2 USE THE & OPERATOR

#  LIKE  {1,2}∩{2,3}={2}

set1 = {1, 2, 3}

set2 = {3, 4, 5}

set3 = {6, 8, 9}

set4 = {9, 8, 73}

intersection_set1 = set1.intersection(set2)  # USE OF intersection

intersection_set2 = set3  & set4                 #USE OF & OPERATOR

print ('The intersection of set1 and set2 is', intersection_set1)

print ('The intersection of set3 and set4 is', intersection_set2)

OUTPUT

The intersection of set1 and set2 is {3}

The intersection of set3 and set4 is {8, 9}



(3).       Difference (-) Operator:- The difference (subtraction) of two sets can be calculated by using the subtraction (-) operator. The resulting set will be obtained by removing all the elements from set 1 that are present in set 2.

EXAMPLE:-

Days1={"Mon","Tue","Wed","Sat"}

Days2={"Thr","Fri","Sat","Sun","Mon"}

print(Days1 - Days2)

OUTPUT:-

{'Tue', 'Wed'}

 

EXAMPLE 2 USE OF difference (subtraction)

# LIKE If A={1,2,3} and B={3,5}, then AB={1,2}

set1 = {1, 2, 3}

set2 = {3, 4, 5}

set3 = {6, 8, 9}

set4 = {9, 8, 73}

difference_set1 = set1.difference(set2)    # USE OF difference

difference_set2 = set3 - set4     # USE OF ( ) OPERATOR

print ('The difference between set1 and set2 is', difference_set1)

print ('The difference between set3 and set4 is', difference_set2)

OUTPUT

The difference between set1 and set2 is {1, 2}

The difference between set3 and set4 is {6}

(4).       SET SYMMETRIC DIFFERENCE OPERATOR:- The symmetric difference of two sets consists of elements that are present in either set but not in both sets. The symmetric difference of A and B is denoted by "A Δ B" and is defined by .- (hyphen)  ( means The symmetric difference between two sets is the set of all the elements that are either in the first set or the second set but not in both.)

Python provides the symmetric_difference() function or the ^ operator to perform this operation. The resulting set contains elements that are unique to each set.

EXAMPLE OF SET SYMMETRIC

#LIKE  :- A Δ B = (A − B) &Union; (B − A)

set1 = {1, 2, 3}

set2 = {3, 4, 5}

set3 = {6, 8, 9}

set4 = {9, 8, 73}

symmetric_difference_set1 = set1.symmetric_difference(set2)  #USE OF symmetric_difference

symmetric_difference_set2 = set3 ^ set4    #USE OF Caret (computing) (^)

print ('The symmetric difference of set1 and set2 is', symmetric_difference_set1)

print ('The symmetric difference of set3 and set4 is', symmetric_difference_set2)

OUTPUT

The symmetric difference of set1 and set2 is {1, 2, 4, 5}

The symmetric difference of set3 and set4 is {73, 6}



SET FUNCTIONS:-  Python contains the following methods to be used with the sets. Those are

(1) len(set) (2) max(set) (3) min(set) (4) sum(set) (5) sorted(set) (6) set()  (7)  add()  (8) update()

(9) discard()  (10)  remove()   (11)  pop()  (12)  clear()   (13)   union()   (14) intersection()  (15) difference()  (16) symmetric_difference()  (17) issubset()   (18)  issuperset() (19). isdisjoint()

 

(1).       len():- In Python len() is used to find the length of set, i.e it returns the number of items in the set.

Syntax:-    len(set)

EXAMPLE:

num={1,2,3,4,5,6}

print(“length of set :”,len(num))

OUTPUT:-   length of set : 6

(2).       max():-  In Python max() is used to find maximum value in the set.

Syntax:-    max(set)

Example:

num={1,2,3,4,5,6}

lang={'java','c','python','cpp'}

print("Max of set :",max(num))

print("Max of set :",max(lang))

OUTPUT

Max of set : 6

Max of set : python

(3).       min():-  In Python min() is used to find minimum value in the set.

Syntax:-    min(set)

EXAMPLE:-

num={1,2,3,4,5,6}

lang={'java','c','python','cpp'}

print("Min of set :",min(num))

print("Min of set :",min(lang))

OUTPUT:-

Min of set: 1

Min of set : c

(4)        sum():-   In python, sum(set) function returns sum of all values in the set. Set values must in number type.

Syntax:-   sum(set)

example:

num={1,2,3,4,5,6}

print(“sum of set items :”,sum(num))

OUTPUT:-     sum of set items: 21

(5).       sorted():-    In python, sorted (set) function is used to sort all items of set in an ascending order. It also sorts the items into descending and ascending order. It takes an optional parameter 'reverse' which sorts the set into descending order.

Syntax:   sorted (set[,reverse=True])

EXAMPLE:-

num={1,3,2,4,6,5}

lang={'java','c','python','cpp'}

print(sorted(num))

print(sorted(lang))

print(sorted(num,reverse=True))

OUTPUT:

{1, 2, 3, 4, 5, 6}

{'c', 'cpp', 'java', 'python'}

{6, 5, 4, 3, 2, 1}



(6)        set():-    The set() method takes sequence types and converts them to sets. This is used to convert a given string or list or tuple into set

Syntax:-     set(sequence)

EXAMPLE:-

set1=set("PYTHON")  #To convert in string

print(set1)

days=["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"] #To convert in list

set2 = set(days) 

print(set2)

days=("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun") #To convert in tuple

set3 = set(days)

print(set3)

OUTPUT:

{'N', 'O', 'T', 'H', 'P', 'Y'}# now converted in to set

{'Fri', 'Thur', 'Tue', 'Sun', 'Mon', 'Sat', 'Wed'}# now converted in to set

{'Fri', 'Thur', 'Tue', 'Sun', 'Mon', 'Sat', 'Wed'}# now converted in to set

(7).       add():-    In python, the add() method used to add some particular item to the set.(Sum nahi karega)  (By add() method only one item will add at a time not more than one item)

Syntax:-    set.add (item)

EXAMPLE:

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"} 

print("\n printing the original set ... ") 

print(Days)

Days.add("Saturday");

Days.add("Sunday");

print("\n Printing the modified set...");

print(Days)

OUTPUT:

printing the original set ...

{'Wednesday', 'Friday', 'Thursday', 'Tuesday', 'Monday'} # can’t print in sequential order, it will print any random order

 Printing the modified set...

{'Wednesday', 'Sunday', 'Friday', 'Thursday', 'Tuesday', 'Saturday', 'Monday'}# can’t print in sequential order, it will print any random order

(8)        update():-   Python provides the update () method to add more than one item in the set. (update se bhi item ko add karte hai but more than one items at a time)

Syntax:-      set.update ([item1, item2…])

EXAMPLE:

Months={"Jan","Feb","Mar","Apr"}

print("\n Printing the original set ... ") 

print(Months)

Months.update (["May","Jun","Jul"])

print("\n Printing the modified set...");

print(Months)

OUTPUT:

Printing the original set ...

{'Mar', 'Apr', 'Jan', 'Feb'}

 Printing the modified set...

{'Mar', 'Apr', 'Jan', 'Jun', 'May', 'Jul', 'Feb'}



(9).       discard():-   Python provides discard () method which can be used to remove the items from the set. If item doesn't exist in the set, the python will not give the error. The program maintains its control flow.

SYNTAX:-    set.discard (item)

EXAMPLE:- 

Months={"Jan","Feb","Mar","Apr"}

print("\n printing the original set ... ") 

print(Months)

Months.discard("Apr")

print("\n Printing the modified set...");

print(Months)

Months.discard("May")                      #doesn’t give error

print("\n Printing the modified set...");

print(Months)

OUTPUT:-

printing the original set ...

{'Jan', 'Apr', 'Mar', 'Feb'}

 Printing the modified set...

{'Jan', 'Mar', 'Feb'}

 Printing the modified set...

{'Jan', 'Mar', 'Feb'}

(10).     remove():-    Python provides remove () method which can be used to remove the items from the set. If item doesn't exist in the set, the python will give the error.

SYNTAX:-    set.remove (item)

EXAMPLE:-

Months={"Jan","Feb","Mar","Apr"}

print("\n printing the original set ... ") 

print(Months)

Months.remove("Apr")

print("\n Printing the modified set...");

print(Months)

Months.remove("May")                      #it give error

print("\n Printing the modified set...");

print(Months)

OUTPUT:-

printing the original set ...

{'Feb', 'Jan', 'Apr', 'Mar'}

Printing the modified set...

{'Feb', 'Jan', 'Mar'}

KeyError: 'May' doesn’t exist.

(11).     pop():-    In Python, pop () method is used to remove the item. However, this method will always remove the last item.

SYNTAX:-     set.pop ()

EXAMPLE:-

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"} 

print("\n printing the original set ... ") 

print(Days)

Days.pop()

print("\n Printing the modified set...");

print(Days)

OUTPUT:_

Printing the original set...

{'Monday', 'Wednesday', 'Friday', 'Tuesday', 'Thursday'}

Printing the modified set...

{'Wednesday', 'Friday', 'Tuesday', 'Thursday'}


(12).     clear():--   In Python, clear () method is used to remove the all items in set.

SYNTAX:-     set.clear ()

EXAMPLE:-

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"} 

print("\n printing the original set ... ") 

print(Days)

Days.clear()

print("\n Printing the modified set...");

print(Days)

OUTPUT:-

printing the original set ...

{'Monday', 'Wednesday', 'Friday', 'Tuesday', 'Thursday'}

Printing the modified set...

set()

(13).     issubset():-   (set1 <=set2)   The issubset() method returns True if all elements of a set are present in another set (passed as an argument). If not, it returns False. (means , set1 ka koi bhi item set2 me present hai to it will return True, otherwise it will return False)

SHORTER SYNTAX 1:-  

set1 <= set2

EXAMPLE:-

set1 = {"a", "b", "c"}

set2 = {"f", "e", "d", "c", "b", "a"}

set3 = set1 <= set2

print(z)

OUTPUT:- True

SYNTAX 2:-

 set1.issubset (set2)

EXAMPLE:-

set1={1,2,3,4}

set2={1,2,3,4,5,6,7,8,9}

print(set1.issubset(set2))# . (means , set1 ka all  items set2 me present hoga to it will return True, so it will be say set1 is subset of set2)

print(set2.issubset(set1))# . (means , set2 ka all items set1 me present hai to it will return True. otherwise it will return False, to yeha per set2 ka all items present nahi hai set1 me)

OUTPUT:-

True

False

(14).     issuperset():-  (set1>=set2)  The issuperset () method returns True if a set has every elements of another set (passed as an argument). If not, it returns False. (set2 is superset of set1)

(The set1 >= set2 operator checks if set1 is a superset of set2. This means that every element in set2 must also be present in set1. If this condition is true, the expression evaluates to True; otherwise, it evaluates to False. )

EXAMPLE 1:-

set1 = {1, 2, 3, 4, 5}

set2 = {2, 3, 5}

set3 = {1, 6}

# Check if set1 is a superset of set2

print(set1 >= set2)

# Check if set1 is a superset of set3

print(set1 >= set3)

OUTPUT:-

True

False

 

SYNTAX:-     set1.issuperset (set2)

EXAMPLE:-

set1={1,2,3,4}

set2={1,2,3,4,5,6,7,8,9}

print(set1.issuperset(set2))# . (means ,just apposite of issubset() method set2 ka all items set1 me present hai to it will return True, example me set2 ka all items present nahi hai, it will return False)

print(set2.issuperset(set1))# . (means , set1 ka all items set2 me present hai to it will return True, otherwise it will return False)

OUTPUT:-

False

True



(16).     isdisjoint():-   The python isdisjoint() method is used to return a True if two sets have a null intersection which means in both sets not have any common value otherwise it returns a false. (means set1 ka koi bhi item set2 me nahi hona chahiye, than it will return True otherwise it will return False)

set1={2,4,6,8,10,12,14}

set2={7,9,5}

set1. isdisjoint(set2)

OUTPUT:-   True

 

COMPARING THE PERFORMANCE OF SETS AND LISTS:-

PERFORMANCE COMPARISON TABLE

S.No

FEATURE

LIST

SET

1

Data Structure

Dynamic Arrays

Hash Tables

 (A Hash Table is a data structure designed to be fast to work with.

The reason Hash Tables are sometimes preferred instead of arrays or linked lists is because searching for, adding, and deleting data can be done really quickly, even for large amounts of data. )

2

How Elements Are Stored

Elements are stored in contiguous memory blocks with specific indices.

Elements are stored using hash values that point to locations in memory.

3

Membership Test (in)

O(n) (linear search, checks each element)

O(1) (constant time due to hashing)

4

Add an Element

O(1) (amortized, but may require resizing)

O(1) (constant time, no resizing needed)

5

Remove an Element

O(n) (may require shifting elements)

O(1) (constant time, no shifting needed)

6

Iterate Over Elements

O(n) (linear, each element must be visited)

O(n) (linear, each element must be visited)

7

Duplicates

Can contain duplicates.

Only unique elements, duplicates are automatically removed.

8

Order

Maintains order of insertion.

Unordered collection of elements.



INTRODUCTION TO DICTIONARIES:-  A dictionary is a kind of data structure that stores items in key-value pairs.  In Python, a dictionary is a built-in data type that stores data in key-value pairs. It is an unordered, mutable, and indexed collection. Each key in a dictionary is unique and maps to a value. Python's dictionary is an example of a mapping type. A mapping object 'maps' the value of one object to another. To establish mapping between a key and a value, the colon (:) symbol is put between the two.

FOLLOWING ARE THE KEY FEATURES OF DICTIONARIES :-

a)      Unordered − The elements in a dictionary do not have a specific order.

b)      Mutable − You can change, add, or remove items after the dictionary has been created.

c)      Indexed – We can’t access the value of the dictionary by the index number,  Although dictionaries do not have numeric indexes.

d)     Unique Keys − Each key in a dictionary must be unique. If you try to assign a value to an existing key, the old value will be replaced by the new value.

e)      Heterogeneous − Keys and values in a dictionary can be of any data type.

 

 CREATING A DICTIONARY:-

 Rules of dictionary creation:-

a)      To create a dictionary, we use curly brackets { } .

b)      Between these curly brackets, we write key-value pairs separated by a comma.

c)      For the key-value pairs, we write the key followed by a colon, a space, and the value that corresponds to the key.

(1)        EMPTY DICTIONARY CREATION :-

var={}

OR

var=dict{} # dict is the key word

print(type(var))

OUTPUT

<Class  ‘dict’>

EXAMPLE:

var={“ajay” : “kmpmvc”,”Age”:40} #here ajay is the key and kmpmvc is the value of the key (ajay)

print(type(var))

print(var)

OUTPUT

{“ajay” : “kmpmvc”,”Age”:40}

(2).       NOW I AM TRYING TO CREATE DUPLICATE VALUE

var={“ajay” : “kmpmvc”,”Age”:40,”ajay”:”kmpmvc”}  #here I am trying to create duplicate value, it will not allowed (Note:- here duplicate key (“ajay”) is not allowed but duplicate

value  ”kmpmvc“ is allowed)

print(type(var))

print(var)

OUTPUT

<Class ‘dict”>

NameError : name ‘name’ is not defined


 

(3)        NOW I WILL ACCESS THE VALUE BY KEY:-

var={“name” : “kmpmvc”,”Age”:40}

print(type(var))

print(var[“name”]) # name is a key so we can access the value of  name

OUTPUT

<Class ‘dict”>

kmpmvc

NOW PER DEFINE METHODS OF DICTIONARY  :-

Function

Description

pop()

Removes the item with the specified key.

update()

Adds or changes dictionary items.

clear()

Remove all the items from the dictionary.

keys()

Returns all the dictionary's keys.

values()

Returns all the dictionary's values.

get()

Returns the value of the specified key.

popitem()

Returns the last inserted key and value as a tuple.

copy()

Returns a copy of the dictionary.

(1).       pop():-    The pop() method eliminates an item from the dictionary and returns the associated value. It takes two arguments: the key of the item to remove and an optional default value. Should the key not exist, the pop() method returns the default value or raises a KeyError if no default is provided.

EXAMPLE:-

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}

d.pop('Age')

print(d.pop(“Age’)) # yeha delete bhi karega and display karega ki koin sa item delete hua hai

print(d)

OUTPUT:-

19

{'Name': 'Ram', 'Country': 'India'}



(2).       get():-   get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).

SYNTAX :     Dict.get(key, Value)

EXAMPLE:-

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}

print(d.get('Name',”Not found”)) # name (key)  ke corresponding  me jo value rahega uske display karega (“Not found” ye optimal message hai  de bhi sakte hai or nahi bhi de sakte hai, agar message dete hai to key (name) dictionary me present hai to uska key ka value display karega OR agar key (name) present nahi hai to “Not found” ka message display karega.

print(d.get('Gender',”Not available” )) Gender  (key)  ke corresponding  me jo value rahega uske display karega lekin agar key ka value nahi rahega to None display karega.OR we can also give amessage like Not available.

OUTPUT:-

Ram

None OR Not available

(3).       clear() :-  Removes all the elements from the dictionary

EXAMPLE:-

my_dict = {'1': 'sandip', '2': 'For', '3': 'deepak'}

my_dict.clear()

print(my_dict)

OUTPUT:-    {}  # here all items are cleared (remove) from the dictionary 

(4).       keys():-            The keys() method produces a sorted list of all keys present in the dictionary. This list is arranged in a sorted order  (To show all the keys of the dictionary which are present in dictionary )

EXAMPLE:-

d = {'A': 'SANDIP', 'B': 'For', 'C': 'DEEPAK'}

k = d.keys() # here display all keys

x = d.value()# here display all values

print(k)

print(x)

OUTPUT:- 

 dict_keys(['A', 'B', 'C'])

dict_value([ 'SANDIP',  'For', 'DEEPAK'])

(5).       items():-           This  method returns a list of all the key-value pairs in the dictionary as tuples. (to display all keys with values of the keys)

EXAMPLE:-

my_dict = {"apple": 2, "banana": 4, "orange": 6}

print(my_dict.items()) 

 OUTPUT:

 dict_items([('apple', 2), ('banana', 4), ('orange', 6)])

OR from LOOP,  WE CAN DISPLAY THE VALUES OF THE DICTIONARY

foe key , values in  my_dict.items() : 

            print(key, values)

OR

print(key, values, sep=”  :-  “) # sep is the key word, full form separator , by sep we can give the hyphen or space or any other characters between two words .  

(6).       update():-        (Adds or changes dictionary items.), Python's update() method is a built-in dictionary function that updates the key-value pairs of a dictionary using elements from another dictionary or an iterable of key-value pairs. With this method, you can include new data or merge it with existing dictionary entries.

EXAMPLE:-

d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}

d2 = {'Name': 'Neha', 'Age': '22'}

d1.update(d2)

print(d1)

OUTPUT:-    {'Name': 'Neha', 'Age': '22', 'Country': 'India'} # Here new values replaced on old value by update()



(7).       values() :-        The values() method in Python returns a view object containing all dictionary values, which can be accessed and iterated through efficiently.

EXAMPLE:- d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}

print(list(d.values()))

OUTPUT:-

['Ram', '19', 'India']

 

(8).       popitem(): -     (  Returns the last inserted key and value as a tuple.   ), The popitem() method in Python dictionaries is used to remove and return the last inserted key-value pair as a tuple. If the dictionary is empty then it raises a KeyError.

EXAMPLE:-

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}

val = d.popitem()

print(val)

val = d.popitem()

print(val)

OUTPUT:-

('Country', 'India')

('Age', '19')

(9).       copy():-  (  Returns a copy of the dictionary.)   , copy() method returns a shallow copy of the dictionary.

EXAMPLES:-

SYNTAX: -    dict.copy()

original = {1: 'ajay', 2: 'for'}

# copying using copy() function

new = original.copy()

# removing all elements from the list

# Only new list becomes empty as copy()

# does shallow copy.

new.clear()

print('new: ', new)

print('original: ', original)

OUTPUT:-

new:  {}

original:  {1: 'ajay', 2: 'for'}

 

(10).     ADDING NEW ITEM IN THE DICTIONARY :-   We can add new key-value pairs

d = {1: 'ajay', 2: 'For', 3: 'sandip'}

# Adding a new key-value pair

d["age"] = 22

print(d)

OUTPUT:-    {1: 'ajay', 2: 'For', 3: 'ajay', 'age': 22}

(11).     Deleting Variables:-  del keyword can be used to delete variables too.

EXAMPLE:-

a = 20

b = "Sandip Deepak Anshu"

# delete both the variables

del a, b

# check if a and b exists after deleting

print(a)

print(b)

OUTPUT:-

NameError: name 'a' is not defined

(12).     Deleting Dictionary and Removing key-value Pairs:-   We will remove few key-value pairs from a dictionary using del keyword.

d = {"sandip": "anshu", "black": "deepak", "ajay": "mohit"}

 # delete key-value pair with key "deepak" from my_dict1

del d["deepak"]

 # check if the  key-value pair with key "deepak" from d1 is deleted

print(d)

OUTPUT:-    {'sandip': 'anshu', 'ajay': 'mohit'}



LOOPING ITEMS IN DICTIONARY :-        A for loop in Python is a control flow statement that iterates over a sequence of elements. It repeatedly executes a block of code for each item in the sequence. The sequence can be a range of numbers, a list, a tuple, a string, or any iterable object. We can loop through dictionaries using a for loop in Python by iterating over the keys or key-value pairs within the dictionary.

There are two common approaches :-

(1)        Example: Iterating over Keys:-

student = {"name": "Ajay", "age": 21, "major": "Computer Science"}

for key in student:

   print(key, student[key])   # by key

OUTPUT:-

name Ajay

age 21

major Computer Science

(2).       Example: Iterating over Key-Value Pairs

student = {"name": "Ajay", "age": 21, "major": "Computer Science"}

for key, value in student.items():

   print(key, value)   # by value

OUTPUT

name Ajay

age 21

major Computer Science

EXAMPLE BY FUNCTION

states_tz_dict = {

    'Florida': 'EST and CST',

    'Hawaii': 'HST',

    'Arizona': 'DST',

    'Colorado': 'MST',

    }

for k in states_tz_dict.keys():

    print(k)

OUTPUT

Result:

# Florida  

# Hawaii   

# Arizona  

# Colorado

 

EXAMPLE 1:- my_dict = {'apple': 10.5, 'banana': 20.25, 'orange': 0.75}

EXAMPLE 2:-

# Creating a dictionary using curly braces

sports_player = {

   "Name": "Sachin Tendulkar",

   "Age": 48,

   "Sport": "Cricket"

}

print ("Dictionary using curly braces:", sports_player)

# Creating a dictionary using the dict() function

student_info = dict(name="Sandip", age=21, major="Computer Science")

print("Dictionary using dict():",student_info) 

OUTPUT:-

Dictionary using curly braces: {'Name': 'Sachin Tendulkar', 'Age': 48, 'Sport': 'Cricket'}

Dictionary using dict(): {'name': 'Sandip', 'age': 21, 'major': 'Computer Science'}

 

NOW THE UNIT 4 IS OVER



No comments:

Post a Comment

PLEASE DO LEAVE YOUR COMMENTS

UNIT 5 SOFTWARE TESTING (UNIT NAME) :- TEST AUTOMATION TOOLS AND EMERGING TRENDS

  DR. AJAY KUMAR PATHAK  ASSISTANT PROFESSOR READ  ALL THE NOTES CHAPTER WISE   MINOR PAPER   SUBJECT NAME:-   MN–2C (Th):- SOFTWARE TESTING...